#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
#include<unordered_set>
using namespace std;


struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x):val(x), left(nullptr), right(nullptr){}
};


class Solution{
    public:
    void ans1(TreeNode* root){
        if(root == nullptr){
            return;
        }
        vector<TreeNode*> node;
        front(root, node);
        int len = node.size();
        for(int i = 1; i != len; i++){
            TreeNode* pre = node[i-1], * temp = node[i];
            pre->left = nullptr;
            pre->right = temp;
        }
    }

    void front(TreeNode* root, vector<TreeNode*>& node){
        if(root == nullptr){
            return;
        }
        node.push_back(root);
        
        front(root->left, node);
        front(root->right, node);
    }

    void frontTraverse(TreeNode* root, vector<int>& val){
        if(root == nullptr){
            return;
        }
        val.push_back(root->val);
        frontTraverse(root->left, val);
        frontTraverse(root->right, val);
    }

    TreeNode* createTree(vector<int>nums, int index, int len){
        if(nums[index] == '#'){
            return nullptr;
        }
        TreeNode* root = new TreeNode(nums[index]);

        if(index * 2 + 1 < len){
            root->left = createTree(nums, index * 2 + 1, len);
        }else{
            root->left = nullptr;
        }
        if(index * 2 + 2 < len){
            root->right = createTree(nums, index * 2 + 2, len);
        }else{
            root->right = nullptr;
        }

        return root;
    }

    void show(vector<int>& val){
        int len = val.size();
        for(int i = 0; i != len-1; i++){
            cout << val[i] << " " << ends;
        }
        cout << val[len-1] << endl;
        val.clear();
    }


    // ans2
    void flatten(TreeNode* root){
        if(root == nullptr){
            return;
        }
        frontOrder(root);
        TreeNode* temp = root;
        for(int i = 1; i != index; i++){
            temp->right = map[i];
            temp = temp->right;
        }
    }

    void frontOrder(TreeNode* root){
        if(root == nullptr){
            return;
        }
        map[index] = root;
        index++;
        frontOrder(root->left);
        root->left = nullptr;
        frontOrder(root->right);
        root->right = nullptr;
    }
private:
    int index = 0;
    unordered_map<int, TreeNode*> map;

};

void test1(){
    Solution s;
    vector<int> nums = {1,2,5,3,4,'#',6};
    TreeNode* root = s.createTree(nums, 0, nums.size());
    // s.ans1(root);
    s.flatten(root);
    vector<int> val;
    s.frontTraverse(root, val);
    s.show(val);
    
}


int main(void){
    test1();

    return 0;
}